#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

#define LINE_FFLUSH 0
#define FULL_FFLUSH 1
#define NONE_FFLUSH 2

typedef struct MYFILE
{
    int fd;
    char buffer[1024];
    int end;
    int flags;
}MYFILE;

MYFILE* my_fopen(const char* filename,char* mode)
{
    int fd=0;
    if(strcmp("r",mode)==0)
    {
        fd = open(filename,O_RDONLY);
    }
    else if(strcmp("w",mode)==0)
    {
        fd=open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
    }
    else if(strcmp("rw",mode)==0)
    {
        fd=open(filename,O_RDWR|O_CREAT,0666);
    }
    else if(strcmp("a",mode)==0)
    {
        fd=open(filename,O_WRONLY|O_CREAT|O_APPEND,0666);
    }
    MYFILE* myfile=(MYFILE*)malloc(sizeof(MYFILE));
    myfile->fd=fd;
    myfile->end=0;
    myfile->flags=LINE_FFLUSH;
    return myfile;
}

size_t my_fwrite(const void *ptr,size_t n,size_t size,MYFILE* stream)
{
    strncpy(stream->buffer+stream->end,ptr,n);
    stream->end+=n;
    if(stream->buffer[stream->end-1]=='\n')
    {
        write(stream->fd,stream->buffer,stream->end);
        syncfs(stream->fd);
        stream->end=0;

    }
    return n;
}

int my_fclose(MYFILE* fp)
{
    close(fp->fd);
    free(fp);
    return 0;
}

int my_fflush(MYFILE* fp)
{
    if(fp->end > 0)
    {
        write(fp->fd,fp->buffer,fp->end);
        syncfs(fp->fd);
        fp->end=0;
    }
    return 0;
}

int main()
{
    //写
    MYFILE* myfile = my_fopen("log.txt","w");
    char msg[]="hello world";
    my_fwrite(msg,strlen(msg),1,myfile);

    //追加写
    //MYFILE* myfile = my_fopen("log.txt","a");
    //char msg[]="hello world 1\n";
    //my_fwrite(msg,strlen(msg),1,myfile);

    //检验缓冲区、
    //char msg1[]="hello code\n";
    //my_fwrite(msg1,strlen(msg1),1,myfile);

    my_fflush(myfile);
    my_fclose(myfile);
    return 0;
}

